window.geolocation = function () {
  var self = window.geolocation = this;
  var ak = 'cmlN6SWFTGXTwUe4GUAAWWpb';
  // 使用浏览器window.navigator获取
  self.getGeolocation = function (param) {
    navigator.geolocation.getCurrentPosition(function (res) {
      if (typeof param.success == 'function') param.success(res);
    }, function (res) {
      if (typeof param.error == 'function') param.error(res);
      self.geolocationForBaidu(param.success)
    }, {
      enableHighAccuracy: false,
      timeout: 5000,
      maximumAge: 600000
    });
  }

  // 使用百度ip获取经纬度接口
  self.geolocationForBaidu = function (success) {
    const geocoding = document.getElementById('getBdLocation');
    const version = new Date().getTime();
    const src = "https://api.map.baidu.com/location/ip?ak=" + ak + "&callback=geolocationBaiduCallback&coor=bd09ll&version=" + version;
    if (geocoding) geocoding.parentNode.removeChild(geocoding);
    let script = document.createElement("script");
    script.type = "text/javascript";
    script.id = "getBdLocation";
    script.src = src;
    document.body.appendChild(script);
    self.baiduGeolocationData = {}

    var timer = setInterval(function () {
      if (JSON.stringify(self.baiduGeolocationData) != '{}') {
        if (typeof success == 'function') success(self.baiduGeolocationData)
        clearInterval(timer);
      }
    }, 100)
  }
  window.geolocationBaiduCallback = function (res) {
    console.log('geolocationBaiduCallback', res)
    self.baiduGeolocationData = {
      coords: {
        latitude: res.content.point.y, // 纬度
        longitude: res.content.point.x,// 经度
      }
    }
  }

  // 使用百度接口地址解析
  self.geocoder = function (param) {
    var geocoding = document.getElementById('getBdGeocoding');
    var version = new Date().getTime();
    var src = "https://api.map.baidu.com/geocoder/v2/?callback=geocoderBaiduCallback&location="+ param.latitude+','+ param.longitude+"&output=json&pois=1&ak=" + ak + "&version=" + version;
    if (geocoding) geocoding.parentNode.removeChild(geocoding);
    let script = document.createElement("script");
    script.type = "text/javascript";
    script.id = "getBdGeocoding";
    script.src = src;
    document.body.appendChild(script);
    self.baiduGeocoderData = {}

    var timer = setInterval(function () {
      if (JSON.stringify(self.baiduGeocoderData) != '{}') {
        console.log('baiduGeocoderData', self.baiduGeocoderData)
        if (self.baiduGeocoderData.status == 0 && typeof param.success == 'function') {
          param.success(self.baiduGeocoderData.result)
        }else if(typeof param.error == 'function'){
          param.error(self.baiduGeocoderData);
        }
        clearInterval(timer);
      }
    }, 100)
  }
  window.geocoderBaiduCallback = function (res) {
    self.baiduGeocoderData = res;
  }
}